//
//  AppPurchaseManager.swift
//  CocoProject
//
//  Created by Vill on 2023/11/13.
//

import UIKit
import SwiftyStoreKit

class AppPurchaseManager: NSObject {
    
    static func completeTransactions() {
        SwiftyStoreKit.completeTransactions(atomically: true) { purchases in
            for purchase in purchases {
                switch purchase.transaction.transactionState {
                case .purchased, .restored:
                    if purchase.needsFinishTransaction {
                        //处理交易
                        AppPurchaseManager.handleTransaction(transaction: purchase.transaction) { result in
                            AppPurchaseManager.updateBalance()
                        }
                    }
                case .failed, .purchasing, .deferred:
                    break // do nothing
                @unknown default:
                   return
                }
            }
        }
    }
    
    //刷新金币数
    static func updateBalance() {
        COHttpManager.request(target: COBaseApi.mybalance, modelType: COMyBalanceModel.self) { code, object, success in
            var model = COUserInfoManager.shared.curUser
            model?.userResponse.balance = object?.coins ?? 0
            COUserInfoManager.shared.curUser = model
            COUserInfoManager.coSaveInfo()
        } failureBlock: { code, msg in
            print(msg as Any)
        }
    }

    // 获取收据
    static func handleTransaction(transaction:PaymentTransaction,completeHandle:@escaping ((Bool) -> Void)) {
        SwiftyStoreKit.fetchReceipt(forceRefresh: false) { (result) in
            NotificationCenter.default.post(name: .RandomTimeRunNotification, object: nil, userInfo: ["type":0])
            switch result {
                case .success(let receiptData):
                    let encryptedReceipt = receiptData.base64EncodedString(options: .endLineWithLineFeed)
                    self.checkCoinOrder(transaction: transaction, receiptData: encryptedReceipt) { success in
                        completeHandle(true)
                    }
                case .error(_):
                    UIToolHelper.hideHUD()
            }
        }
    }
    
    // 验证订单
    static func checkCoinOrder(transaction: PaymentTransaction, receiptData: String,completeHandle:@escaping ((Bool) -> Void)) {
        var params = [String:Any]()
        if let identifier = transaction.transactionIdentifier {
            params["transactionNumber"] = identifier
        }
        params["receiptData"]   =  receiptData
        params["uuid"]   = HDeviceIdentifier.deviceIdentifier()
        UIToolHelper.showHUD()
        COHttpManager.request(target: COBaseApi.useriOSPay(param: params), modelType: COIosPayMapModel.self) { code, object, success in
            if (success == true){
                if object?.map.status == 0{
                    SwiftyStoreKit.finishTransaction(transaction)
                    completeHandle(true)
                }else if (object?.map.status == 21002 || object?.map.status == 21005) {
                    self.checkCoinOrder(transaction: transaction, receiptData: receiptData, completeHandle: completeHandle)
                }else{
                    SwiftyStoreKit.finishTransaction(transaction)
                    completeHandle(false)
                }
            }else{
                SwiftyStoreKit.finishTransaction(transaction)
                completeHandle(false)
            }
        } failureBlock: { code, msg in
            UIToolHelper.hideHUD()
            UIToolHelper.makeToast("Network error,plesase try again later!")
        }
    }
    
    static func pay(purchaseProductId:String,completeHandle:@escaping (Bool) -> Void) {
        NotificationCenter.default.post(name: .RandomTimeRunNotification, object: nil, userInfo: ["type":1])
        if !SwiftyStoreKit.canMakePayments {
            completeHandle(false)
            return
        }
        SwiftyStoreKit.purchaseProduct(purchaseProductId, quantity: 1, atomically: false) { purchaseResult in
            switch purchaseResult {
            case .success(let purchase):
                //处理交易
                AppPurchaseManager.handleTransaction(transaction: purchase.transaction) { result in
                    completeHandle(result)
                }
            case .error(let error):
                // 倒计时继续
                NotificationCenter.default.post(name: .RandomTimeRunNotification, object: nil, userInfo: ["type":0])
                switch error.code {
                    case .unknown: UIToolHelper.makeToast("Unknown error. Please contact support")
                    case .clientInvalid: UIToolHelper.makeToast("Not allowed to make the payment")
                    case .paymentCancelled: UIToolHelper.makeToast("Cancelled")
                    case .paymentInvalid: UIToolHelper.makeToast("The purchase identifier was invalid")
                    case .paymentNotAllowed: UIToolHelper.makeToast("The device is not allowed to make the payment")
                    case .storeProductNotAvailable: UIToolHelper.makeToast("The product is not available in the current storefront")
                    case .cloudServicePermissionDenied:UIToolHelper.makeToast("Access to cloud service information is not allowed")
                    case .cloudServiceNetworkConnectionFailed: UIToolHelper.makeToast("Could not connect to the network")
                    case .cloudServiceRevoked: UIToolHelper.makeToast("User has revoked permission to use this cloud service")
                    default: UIToolHelper.makeToast((error as NSError).localizedDescription)
                }
                completeHandle(false)
            }
        }
    }

}
